package com.heima.utils.common;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class AppJwtUtil {

    // TOKEN的有效期一天（S）   应该是1小时
    private static final int TOKEN_TIME_OUT = 3600;
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
    // 最小刷新间隔(S)
    private static final int REFRESH_TIME = 300;

    // 生产ID
    public static String getToken(Long id){
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("id",id);
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(currentTime))  //签发时间
                .setSubject("system")  //说明
                .setIssuer("heima") //签发者信息
                .setAudience("app")  //接收用户
                .compressWith(CompressionCodecs.GZIP)  //数据压缩方式
                .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))  //过期时间戳
                .addClaims(claimMaps) //cla信息
                .compact();
    }

    /**
     * 获取token中的claims信息
     *
     * @param token
     * @return
     */
    private static Jws<Claims> getJws(String token) {
            return Jwts.parser()
                    .setSigningKey(generalKey())
                    .parseClaimsJws(token);
    }

    /**
     * 获取payload body信息
     *
     * @param token
     * @return
     */
    public static Claims getClaimsBody(String token) {
        try {
            return getJws(token).getBody();
        }catch (ExpiredJwtException e){
            return null;
        }
    }

    /**
     * 获取hearder body信息
     *
     * @param token
     * @return
     */
    public static JwsHeader getHeaderBody(String token) {
        return getJws(token).getHeader();
    }

    /**
     * 是否过期
     *
     * @param claims
     * @return -1：有效(至少还能使用5分钟)，0：有效(令牌5分钟内就过期)，1：过期，2：过期
     */
    public static int verifyToken(Claims claims) {
        if(claims==null){
            return 1;
        }
        try {
            claims.getExpiration().before(new Date());
            // 需要自动刷新TOKEN
            if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
                return -1;
            }else {
                return 0;
            }
        } catch (ExpiredJwtException ex) {
            return 1;
        }catch (Exception e){
            return 2;
        }
    }

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    public static void main(String[] args) {
       /* Map map = new HashMap();
        map.put("id","11");*/
      // System.out.println(AppJwtUtil.getToken(1102L));
        Jws<Claims> jws = AppJwtUtil.getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWL0QrDIAwA_yXPFdRZq_2bZEmphYIQCxtj_770YW93HPeBYzRYYRbhheThKjG5tBE6iiU4LrVsKWbEJ8MEDQesIcfsw5zyMoFeZLe-dch5d1XTXdqJZnixGfZuLK_-P6u_z2YtBB-_P-tet9KDAAAA.wIn4eq8d0G8R-_AWh9P3aM_PbCEorBrGYa0Y-nq2TQqda56-9sgr3bEiAcH2mXOsnWKGeI7JXEkwM1k7IKAI7A");
        Claims claims = jws.getBody();
        System.out.println(claims);
        System.out.println(claims.get("id"));

//        Claims claimsBody = AppJwtUtil.getClaimsBody("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWMQQrDMAwE_6JzDJYry3V-o9QKdSFgkAMtJX-vfehtl9nZL7x6hRWEN0wYdpdjyo6ikstU2KkkvxcKDy8CC1TpsCIH9hhvTAvYuQ3bPtb1mNxs1KfWY67lLPO6tZH13f7mPU-zDobow_UDtPdTDoMAAAA.9FfaKZduQsJeRvORg_hCRi1Rg0rXBOOiqMsq8SSEG9KG5JVL9c618rC3eFeRUz2qsejR3N7ZRXDlCzM2Pgzebw\n.H4sIAAAAAAAAADWMwQqEMAxE_yVnC02qjfo3cW2xC0IhFXZZ_PdNDzKXGR5vfvBuBVaQTMg5BjdlJjdGYre9vLi4hJC80LwvDAMUabBiRLbMGAbQazNbv9rS2bmqzSOVU2zJtffrWq2nT33MaexmMYbo6f4DhOz5hoMAAAA.LdmdPLSkC5YzAq3STd3a4L4v2WDlO4hpsOnm6zVSGw5sritL1mDnCUMvRdMVb2TT_ndUx3qxKGLslvLOSCcRgg");
//        System.out.println(claimsBody);

//        int i = AppJwtUtil.verifyToken(claimsBody);
//        System.out.println(i);




    }

}
